package com.example.baijiebrower.update;

import android.app.Dialog;
import android.content.Context;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.example.baijiebrower.R;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName UpdateLoad
 * @Author liufeng
 * @Date 2024/9/14
 * @email liufeng@szbaijie.cn
 * @Description
 */
public class UpdateLoad extends Dialog {
    private Context mContext;
    private String mUrl;
    private ExecutorService mExecutorService;
    private NumberProgressBar mNumberProgressBar;
    private Button cancelButton;
    private UpdateJson updateJson;
    public UpdateLoad(@NonNull Context context , String url) {
        super(context);
        this.mContext = context;
        this.mUrl = url;
        setContentView(R.layout.update_load);
        initDialog();
    }

    private void initDialog(){
        mExecutorService = Executors.newFixedThreadPool(1);
        mNumberProgressBar = findViewById(R.id.npb1);
        cancelButton = findViewById(R.id.cancelLoad);
        mExecutorService.execute(updateLoadThread);
        if (cancelButton != null){
            cancelButton.setOnClickListener(v -> {
                mExecutorService.shutdownNow();
                dismiss();
            });
        }
    }

    private Thread updateLoadThread = new Thread(new Runnable() {
        @Override
        public void run() {

            updateJson = new UpdateJson();
            try {
                File file = updateJson.downloadFile(mContext,mUrl,mNumberProgressBar);
                updateJson.installApk(mContext,file);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
}
